<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrappe">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓库名称">
              <a-input v-model="queryParam.storeName" placeholder="请输入仓库名称" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓库所属团队">
              <select-team-input
                :multi="true"
                placeholder="请选择仓库所属团队"
                v-model="queryParam.teamId"
                :teamType="0"
                :tdlx="3"/>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="仓管员">
              <a-input v-model="queryParam.storehouseManagerName" placeholder="请输入仓管员" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="出入库时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-month-picker style="width: 100%" @change="monthChange" v-model="month" placeholder="请选择出入库时间" format="YYYY-MM" valueFormat="YYYY-MM" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="物料大类">
              <a-select
                v-model="queryParam.provisionBroad"
                placeholder="请选择物料大类"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                @change="handleChange"
                :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
              >
                <a-select-option v-for="item in provisionBroadList" :key="item.id" :value="item.id">{{item.categoryName}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="物料小类">
              <a-select
                v-model="queryParam.provisionSmall"
                placeholder="请选择物料小类"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
                @change="handleProvisionSmallChange"
              >
                <a-select-option v-for="item in provisionSmallList" :key="item.id" :value="item.id">{{item.categoryName}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-model-item label="物料名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialName">
              <select-material-input v-model="queryParam.materialName" :materialFlag="false" @back="materialNameBack"/>
            </a-form-model-item>
          </a-col>
          <!-- <template v-if="toggleSearchStatus"></template> -->
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button type="primary" icon="download" @click="handleExportXls('仓库物料汇总表')" :disabled="isDisabledAuth('material:export')">导出</a-button>
    </div>
    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:'140%'}"
        :components="draggableComponent"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        :customRow="customRow"
        @change="handleTableChange">
        <template slot="status" slot-scope="status">
          <a-badge :status="status | statusTypeFilter" :text="status | statusFilter"/>
        </template>
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>
        <span slot="action" slot-scope="text, record">
          <a-button
            class="ruleButton"
            :ghost="true"
            type="primary"
            icon="edit"
            @click="handleEdit(record)"
            :disabled="isDisabledAuth('material:edit')"
        />
        <a-divider type="vertical"/>
        <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
          <a-button
            class="ruleButton"
            :ghost="true"
            type="primary"
            icon="delete"
            :disabled="isDisabledAuth('material:delete')"/>
        </a-popconfirm>
        </span>
      </a-table>
    </div>
  </a-card>
</template>
<script>
  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import {DisabledAuthFilterMixin} from '@/mixins/DisabledAuthFilterMixin'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import {getAction} from '@/api/manage'
  import SelectMaterialInput from '@/views/scy/components/SelectMaterialInput'
  import moment from 'moment';
  export default {
    name: 'MaterialList',
    mixins:[JeecgListMixin, mixinDevice, DisabledAuthFilterMixin],
    components: {
      SelectTeamInput,
      SelectMaterialInput
    },
    data () {
      return {
        description: '仓库物料汇总表',
        //表头
        columns:[],
        //列设置
        settingColumns:[],
        // 列定义
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },

          {
            title:'仓库名称',
            align:"center",
            width:100,
            dataIndex: 'storehouseName',
            ellipsis: true
          },
          {
            title:'仓库所属团队',
            align:"center",
            width:200,
            dataIndex: 'tdmc',
            ellipsis: true
          },
          {
            title:'仓管员',
            align:"center",
            width:100,
            dataIndex: 'storehouseManagerName',
            ellipsis: true
          },
          {
            title:'物料大类',
            align:"center",
            width:200,
            dataIndex: 'provisionBroadName',
            ellipsis: true
          },
          {
            title:'物料小类',
            align:"center",
            width:200,
            dataIndex: 'provisionSmallName',
            ellipsis: true
          },
          {
            title:'物料编号',
            align:"center",
            width:200,
            dataIndex: 'materialBillId',
            ellipsis: true
          },
          {
            title:'物料名称',
            align:"center",
            width:200,
            dataIndex: 'materialName',
            ellipsis: true,
          },
          {
            title:'单位',
            align:"center",
            width:100,
            dataIndex: 'unitName',
            ellipsis: true,
          },
          {
            title:'单价（元）',
            align:"center",
            width:200,
            dataIndex: 'referencePrice',
            ellipsis: true,
          },
          {
            title: '当前库存',
            children: [
          {
            title:'库存数量',
            align:"center",
            dataIndex: 'amount',
            ellipsis: true,
          },
          {
            title:'库存金额（元）',
            align:"center",
            dataIndex: 'priceSum',
            ellipsis: true,
          }
          ]},
          {
            title: '期初库存',
            children: [
          {
            title:'期初数量',
            align:"center",
            dataIndex: 'hisAmount',
            ellipsis: true,
          },
          {
            title:'期初金额（元）',
            align:"center",
            dataIndex: 'hisPriceSum',
            ellipsis: true,
          }
          ]},
          {
            title: '入库',
            children: [
          {
            title:'入库数量',
            align:"center",
            dataIndex: 'inNum',
            ellipsis: true,
          },
          {
            title:'入库金额（元）',
            align:"center",
            dataIndex: 'inPriceSum',
            ellipsis: true,
          }
          ]},
          {
            title: '出库',
            children: [
          {
            title:'出库数量',
            align:"center",
            dataIndex: 'outNum',
            ellipsis: true,
          },
          {
            title:'出库金额（元）',
            align:"center",
            dataIndex: 'outPriceSum',
            ellipsis: true,
          }]}
        ],
        url: {
          list: "/api/erp/workbench/report/material/material/list",
          exportXlsUrl: "/api/erp//workbench/report/material/material/exportXls",
          queryProvisionBroadList: "/api/erp/purchase/material/erpMaterialCategory/queryAllParent",
          queryProvisionSmallList: "/api/erp/purchase/material/erpMaterialCategory/queryChildrenByParentId"
        },
        dictOptions:{},
        superFieldList:[],
        provisionSmallList: [],
        month: moment(),
        queryParam:{
          month: moment().startOf('month').format("YYYY-MM")
        }
      }
    },
    created() {
      this.findProvisionBroadList()
    },
    mounted() {
      this.initQueryParam()
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      materialNameBack(data) {
        const material = data[0]
        this.$set(this.model, 'materialBillId', material.materialBill)// 物料编码
        this.$set(this.model, 'specification', material.specification)// 规格型号
        this.$set(this.model, 'unit', material.unit)// 单位
        this.$set(this.model, 'brand', material.brand)// 品牌
        this.$set(this.model, 'amount', null)//数量
        this.$set(this.model, 'unitPrice', null)//单价
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      findProvisionBroadList() {
        const that = this
        that.provisionBroadList = []
        getAction(this.url.queryProvisionBroadList).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionBroadList.push({ 'id':res.id, 'categoryName':res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      findProvisionSmallList(value) {
        const that = this
        const parentId = value
        getAction(this.url.queryProvisionSmallList, { parentId }).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionSmallList.push({ 'id':res.id, 'categoryName':res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      // 修改大类
      handleChange(value) {
        this.provisionSmallList = []
        // 修改大类清空物料小类和物料名称
        this.$set(this.queryParam, 'provisionSmall', undefined);
        this.$set(this.queryParam,'materialName',null)
        if (!!value) {
          this.findProvisionSmallList(value)
        }
      },
      // 修改小类
      handleProvisionSmallChange(){
        // 修改小类清空物料名称
        this.$set(this.queryParam,'materialName',null)
      },
      monthChange(date,dateString){
        console.log(date)
        console.log(dateString)
        this.queryParam.month = date
      },
      // 初始化查询条件
      initQueryParam(){
        // 所属月份：默认为当月
        let dateNow = new Date()
        let newMonth = dateNow.getFullYear() + '-' + (dateNow.getMonth()+1)
        console.log("当前月份:",newMonth)
        this.queryParam.month = newMonth;
      },searchReset() {
        this.queryParam = {
          month: moment().startOf('month').format("YYYY-MM"),
        }
        this.searchQuery()
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
